<template>
  <div  class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="姓名搜索" style="width: 200px;" class="filter-item" clearable />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button
        v-permissionCode="'person:manager:add'"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建人员
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="exportExcel"
      >
        导出到excel
      </el-button>
    </div>
    <el-table :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.gender }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="身份证号">
        <template slot-scope="scope">
          <span>{{ scope.row.idCardNo }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-table id="exportTable" :data="exportTableData" hidden border fit highlight-current-row style="width: 100%" height="600">
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.gender }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{ scope.row.mobile }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="身份证号">
        <template slot-scope="scope">
          <span>{{ scope.row.idCardNo }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNumber"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :fullscreen="false"
    >
      <el-row>
        <el-col :span="8">
          <el-upload
            ref="uploadImage"
            class="avatar-uploader"
            :action="imageUploadUrl"
            :multiple="false"
            :limit="1"
            :auto-upload="false"
            :on-preview="handlePicturePreview"
            :data="uploadExtraData"
            :on-success="onUploadSuccess"
            :on-change="onUploadChange"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <el-button @click="btnUploadImage">
            上传图片
          </el-button>
          <el-dialog :visible.sync="imageDialogVisible" append-to-body>
            <img width="100%" :src="imageDialogImageUrl" alt="">
          </el-dialog>

        </el-col>
        <el-col :span="16">
          <el-form
            ref="dataForm"
            :rules="rules"
            :model="temp"
            label-position="left"
            label-width="70px"
            style="width: 400px; margin-left:50px;"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-input v-model="temp.gender" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="temp.mobile" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idCardNo">
              <el-input v-model="temp.idCardNo" />
            </el-form-item>
            <el-form-item label="图片路径" prop="imgUrl">
              <el-input v-model="temp.imgUrl" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { getToken } from '@/utils/auth'
import { getPersonList, createOrUpdate, deletePerson } from '@/api/person'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 当然你也可以为了方便使用，将它注册到全局
import permissionCode from '@/directive/permissionCode/index.js' // 权限判断指令
import { MessageBox } from 'element-ui'
import bus from '@/utils/eventBus'

export default {
  name: 'Persons',
  components: { Pagination },
  directives: { waves, permissionCode },
  data() {
    return {
      token: '',
      list: null,
      exportTableData: null,
      listLoading: true,
      total: 0,
      listQuery: { // 查询列表时的参数对象
        pageNumber: 1,
        pageSize: 10,
        search: undefined,
        tenantId: undefined
      },
      temp: {
        id: undefined,
        tenantId: undefined,
        name: '',
        gender: '',
        mobile: '',
        idCardNo: '',
        imgUrl: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      imageDialogVisible: false,
      imageDialogImageUrl: '',
      imageFormModel: {},
      imageUrl: '',
      finalSelectedFile: null, // 最终选择上传的图片文件
      rules: {
        name: [{ required: true, message: '姓名必填', trigger: 'blur' }],
        gender: [{ required: true, message: '性别必填', trigger: 'blur' }],
        mobile: [{ required: true, message: '手机号必填', trigger: 'blur' }],
        idCardNo: [{ required: true, message: '身份证号必填', trigger: 'blur' }],
        imgUrl: [{ required: true, message: '图片一定要上传', trigger: 'blur' }]
      }
    }
  },
  computed: {
    uploadExtraData() {
      return {
        'app': 'siti-framework',
        'type': 'headImage'
      }
    },
    imageUploadUrl() {
      return process.env.VUE_APP_FILESERVER_API + '/uploadfile.jsp?token=' + this.token
    }
  },
  created() {
    this.token = getToken()
    this.getList()
    // 监听 租户改变的事件,选择不同租户后,立马刷新数据
    bus.$on('selectedTenantIdChanged', ()=>{
      this.getList()
    })
  },
  methods: {
    async getList() { // 获取列表数据
      this.listLoading = true
      this.listQuery.tenantId = this.$store.getters.selectedTenantId
      const { content } = await getPersonList(this.listQuery)
      this.list = content.list
      this.total = content.totalCounts
      this.listLoading = false
    },
    handleCreate() {
      if (this.listQuery.tenantId == undefined) {
        MessageBox('必须先选择一个特定的租户,才能继续操作')
        return
      }
      this.resetTemp()
      // 清空图片文件
      this.imageUrl = ''
      this.finalSelectedFile = null
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['uploadImage'].clearFiles()
      })
    },
    handleUpdate(row) {
      console.log('row--->', row)
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      // 显示图片
      this.imageUrl = process.env.VUE_APP_FILESERVER_API + '/' + this.temp.imgUrl + '?token=' + this.token
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deleteData = Object.assign({}, row) // copy obj
        deletePerson(deleteData.id).then(() => {
          // 刷新列表数据
          this.getList()
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
      })
    },
    resetTemp() {
      // 清空temp对象
      Object.keys(this.temp).forEach(key => {
        this.temp[key] = null
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (!this.checkImageUpload()) {
          //   return
          // }
          this.temp.tenantId = this.$store.getters.selectedTenantId
          createOrUpdate(this.temp).then(() => {
            // 刷新列表数据
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (!this.checkImageUpload()) {
          //   return
          // }
          const tempData = Object.assign({}, this.temp)
          createOrUpdate(tempData).then(() => {
            // 更新该行数据
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    handlePicturePreview(file) {
      this.imageDialogImageUrl = file.url
      this.imageDialogVisible = true
    },
    // 检查图片上传是否合法
    checkImageUpload() {
      const selectedImageList = this.$refs['uploadImage'].$refs['upload-inner'].fileList
      if (selectedImageList.length === 0) {
        this.$message.error('请上传头像')
        return false
      }
      const file = selectedImageList[0]
      const fileName = file.name.toString()
      const isLt10M = file.size / 1024 / 1024 < 10

      if (fileName.endsWith('.jpg') || fileName.endsWith('.jpeg') || fileName.endsWith('.png')) {
      } else {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
        return false
      }
      return true
    },
    // 导出到excel
    async exportExcel() {
      const listQuery = { // 导出列表时的参数对象
        pageNumber: 1,
        pageSize: 100000
      }
      const { content } = await getPersonList(listQuery, this.token)
      this.exportTableData = content.list
      this.$nextTick(() => {
        var xlsxParam = { raw: true } // 转换成excel时，使用原始的格式
        var wb = XLSX.utils.table_to_book(document.querySelector('#exportTable'), xlsxParam)
        var wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'array'
        })
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: 'application/octet-stream;charset=utf-8' }),
            '人员登记表.xlsx'
          )
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      })
    },
    btnUploadImage() {
      if (!this.finalSelectedFile) {
        alert('请先选择图片')
        return
      }
      this.$refs['uploadImage'].uploadFiles.push(this.finalSelectedFile)
      this.$refs['uploadImage'].submit()
    },
    // 上传文件成功回调
    onUploadSuccess(response, file, fileList) {
      console.log('upload image result--->', response)
      this.temp.imgUrl = response.fileUrl
    },
    onUploadChange(file, fileList) {
      this.finalSelectedFile = file // 每次选择文件时 均赋值给this.finalSelectedFile
      this.$refs['uploadImage'].clearFiles()
      this.imageUrl = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
